<?php

namespace App\Services;

use App\Models\SysRegion as Sys_region;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\Cache;

class SysRegion extends BaseService
{
    use HelperTrait;

    public $cache_name = 'sys_regions';

    public function getAreas()
    {
        $area_model = new Sys_region();
        $list       = [];
        $cache_name = $this->cache_name;
        if (!Cache::has($cache_name)) {
            $area_list1 = $area_model->where('level_id', 1)->select('id', 'parent_id', 'name', 'code')->orderBy('id', 'asc')->get()->toArray();
            $area_list2 = $area_model->where('level_id', 2)->select('id', 'parent_id', 'name', 'code')->orderBy('id', 'asc')->get()->toArray();
            $area_list3 = $area_model->where('level_id', 3)->select('id', 'parent_id', 'name', 'code')->orderBy('id', 'asc')->get()->toArray();

            foreach ($area_list1 as $k => $v) {
                $list[$k] = $v;
                foreach ($area_list2 as $k1 => $v1) {
                    if ($v['id'] == $v1['parent_id']) {
                        $list[$k]['children'][] = $v1;
                        $count = count($list[$k]['children']) - 1;
                        foreach ($area_list3 as $k2 => $v2) {

                            if ($v['id'] == $v1['parent_id'] && $v1['id'] == $v2['parent_id']) {
                                $list[$k]['children'][$count]['children'][] = $v2;
                            }
                        }

                    }
                }
            }

            Cache::set($cache_name, $list);
        }else {
            $list = Cache::get($cache_name);
        }
//            dd($list[0]);
        return $this->format($list);
    }

    // 清空缓存
    public function clearCache()
    {
        $rs = Cache::forget($this->cache_name);
        return $this->format($rs);
    }
}
